package com.wu.server.service;

import com.alibaba.fastjson.JSON;
import com.wu.server.code.Code;
import com.wu.server.config.EncodeJson;
import com.wu.server.dao.GoodsRepository;
import com.wu.server.entity.Goods;
import com.wu.server.websocket.GoodsPrinceSalesWebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.websocket.EncodeException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 商品价格销量图
 * @author Wugs
 * @version 1.0
 * @date 2021/3/3 23:30
 */
@Service
public class GoodsPrinceSalesServer {
    @Autowired
    GoodsRepository goodsRepository;
    @Autowired
    EncodeJson encodeJson;
    @Autowired
    Code code;
    @Async
    public void execute(){
        HashMap<String ,Object> result = new HashMap<>();//定义返回结果
        HashMap<String,Object> meta = new HashMap<>();
        HashMap<String ,Object> data = new HashMap<>();//价格对象和销量对象
        List<Integer> salesData = new ArrayList<>(); //销量数组
        List<Integer> xAxis = new ArrayList<>();//x轴价格数组
        List<Integer> goodsNumber = new ArrayList<>();//价格对应商品数量数组
        int sales= 0;//销量
        int during = 200; //增长范围
        for (int i =0;i*during<15000;i++){
            Integer start = during*i;
            Integer end = during*(i+1);
            Iterable<Goods> goodsList = goodsRepository.getGoodsByPrinceBetween(start,end);
            sales = getGoodsSales(goodsList);
            xAxis.add(end);
            salesData.add(sales);
            goodsNumber.add((int) goodsList.spliterator().getExactSizeIfKnown());
        }
        meta.put("code", code.PRICENUM);
        meta.put("msg",code.getMsg(code.PRICENUM));
        result.put("meta",meta);
        result.put("xAxis",xAxis);
        data.put("goodsNum",goodsNumber);
        data.put("sales",salesData);
        result.put("series",data);
        try {
            GoodsPrinceSalesWebSocket.sendMessage(encodeJson.encode(result));
        } catch (EncodeException e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取区间商品销售量
     * @param goodsList
     * @return
     */
    private Integer getGoodsSales(Iterable<Goods> goodsList){
        int sales = 0;
        for (Goods goods : goodsList){
            sales+=goods.getSales();
        }
        return sales;
    }
}
